﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;

namespace Flagwind.Data.Providers
{
	/// <summary>
	/// Access 数据访问提供程序类。
	/// </summary>
	public sealed class Access : OleDb
	{
		#region 公共属性

		/// <summary>
		/// 当前数据库的类型枚举。
		/// </summary>
		public override DataProviderType ProviderType
		{
			get
			{
				return DataProviderType.Access;
			}
		}

		#endregion

		#region 获取方法

		/// <summary>
		/// 根据参数名和值返回参数一个新的参数对象。
		/// </summary>
		/// <param name="name">参数名。</param>
		/// <param name="value">参数值。</param>
		/// <returns>特定于数据源的参数对象。</returns>
		public override IDataParameter GetParameter(string name, object value)
		{
			var parameter = base.GetParameter(name, value);
			if(value is DateTime)
			{
				((OleDbParameter)parameter).OleDbType = OleDbType.DBTimeStamp; //时间带毫秒将失败
				DateTime dt = (DateTime)value;
				DateTime objDt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
				parameter.Value = objDt;
			}
			return parameter;
		}

		/// <summary>
		/// 获取一个新参数对象。
		/// </summary>
		/// <param name="name">参数名字。</param>
		/// <param name="type">>数据库数据类型。</param>
		/// <returns>特定于数据源的参数对象。</returns>
		public override IDataParameter GetParameter(string name, DbType type)
		{
			var parameter = this.GetParameter();
			parameter.ParameterName = name;
			parameter.DbType = type;
			if(type == DbType.DateTime)
			{
				((OleDbParameter)parameter).OleDbType = OleDbType.DBDate;
			}
			return parameter;
		}

		/// <summary>
		/// 获取一个新参数对象。
		/// </summary>
		/// <param name="name">参数名字。</param>
		/// <param name="type">数据库数据类型。</param>
		/// <param name="size">字段大小。</param>
		/// <returns>特定于数据源的参数对象。</returns>
		public override IDataParameter GetParameter(string name, System.Data.DbType type, int size)
		{
			var parameter = new OleDbParameter();
			parameter.ParameterName = name;
			parameter.DbType = type;
			parameter.Size = size;
			if(type == DbType.DateTime)
			{
				parameter.OleDbType = OleDbType.DBDate;
			}
			return parameter;
		}

		/// <summary>
		/// 获取当前数据库类型的参数数据类型名称。
		/// </summary>
		/// <param name="parameter"></param>
		/// <returns></returns>
		public override string GetNativeDbTypeName(IDataParameter parameter)
		{
			var type = ((OleDbParameter)parameter).OleDbType;
			if(type == OleDbType.VarWChar)
			{
				type = OleDbType.VarChar;
			}
			else if(type == OleDbType.DBDate)
			{
				type = OleDbType.Date;
			}
			else if(type == OleDbType.DBTimeStamp)
			{
				type = OleDbType.Date;
			}
			else if(type == OleDbType.Boolean)
			{
				return "YESNO";
			}
			return type.ToString();
		}

		#endregion
	}
}